package cn.myfirefly.moming.portal.dao;

import java.util.ArrayList;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import cn.myfirefly.moming.common.model.RoleDto;
import cn.myfirefly.moming.portal.dao.mapper.MmRoleMapper;
import cn.myfirefly.moming.portal.entity.MMRole;
import cn.myfirefly.moming.portal.model.RoleFilterDto;
import cn.myfirefly.moming.portal.model.RoleManageSearchDto;
import cn.myfirefly.core.BaseFilterDao;
import cn.myfirefly.core.model.PageResultDto;
import cn.myfirefly.utils.FilterUtil;
import cn.myfirefly.utils.StrUtil;

@Repository
public class RoleDao extends BaseFilterDao<MMRole, RoleFilterDto>{
	
	@Autowired
	private MmRoleMapper mmRoleMapper;
	
	public MMRole getByName(String roleName) {
		Session session = sessionFactory.getCurrentSession();
		MMRole role = null;
		Query query = session.createQuery("from " + MMRole.class.getCanonicalName() + " r where r.roleName=? ");
		query.setString(0, roleName);
		@SuppressWarnings("unchecked")
		List<MMRole> list = query.list();
		if (list != null && list.size() > 0) {
			role = list.get(0);
		}
		return role;
	}
	
	@SuppressWarnings({ "unchecked", "rawtypes" })
	public PageResultDto<MMRole> getList(RoleDto dto) {
		Session session = sessionFactory.getCurrentSession();
		PageResultDto resultDto = new PageResultDto();
		
		StringBuffer countSql = new StringBuffer("select count(r) from " + MMRole.class.getCanonicalName() + " r where 1=1 ");
		StringBuffer querySql = new StringBuffer("from " + MMRole.class.getCanonicalName() + " r where 1=1 ");
		
		List paramList = new ArrayList();
		if (StrUtil.notBlank(dto.getRoleName())) {
			countSql.append(" and r.roleName like ? ");
			querySql.append(" and r.roleName like ? ");
			paramList.add("%" + dto.getRoleName() + "%");
		}
		
		Query query = session.createQuery(countSql.toString());
		FilterUtil.setQueryParams(query, paramList);
		Number number = (Number)query.uniqueResult();
		resultDto.setTotal(number.intValue());
		if (number.intValue() > 0) {
			query = session.createQuery(querySql.toString());
			FilterUtil.setQueryParams(query, paramList);
			List<MMRole> list = query
					.setFirstResult((dto.getPageCurrent() - 1) * dto.getPageSize())
					.setMaxResults(dto.getPageSize())
					.list();
			resultDto.setPageCurrent(dto.getPageCurrent());
			resultDto.setList(list);
		}
		return resultDto;
	}
	
	public List<RoleManageSearchDto> getRolesByLoginName(String loginName) {
		List<RoleManageSearchDto> result = mmRoleMapper.getRolesByLoginName(loginName);
		return result;
	}
}
